package com.bridgeintelligent.tag.customer.controller;

import com.bridgeintelligent.tag.constants.Permissions;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.exception.CustomersException;
import com.bridgeintelligent.tag.customer.pojo.Customers;
import com.bridgeintelligent.tag.customer.pojo.CustomersApprovalRecord;
import com.bridgeintelligent.tag.customer.pojo.ExportSet;
import com.bridgeintelligent.tag.customer.service.ICustomerApprovalService;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.FieldHandler;
import com.bridgeintelligent.tag.utils.SecurityHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 客群审批控制层
 */

@Api(tags = "客群审批")
@RestController
@RequestMapping("/api/customerApproval")
@Slf4j
public class CustomerApprovalController {

    @Autowired
    private ICustomerApprovalService customerApprovalService;

        //-----------------------------客群导出审批流程-----------------------------------------------

    /**
     * 导出客群提交审批
     * //@param exportSet
     * @return
     */
    @ApiOperation(value = "导出提交审批", notes = "导出客群提交审批")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "exportSet", value = "SET设置")
    })
    @PostMapping("/addCommit")
    public Result addCommit(@RequestBody ExportSet exportSet) {
        log.info("exportSet="+exportSet.toString());
        try{
            boolean pass = customerApprovalService.checkExportSetting(exportSet);
            if(!pass){
                return new Result(-1, "客群导出名称重复，请修改客群导出名称后重新提交审批！");
            }
            User user = TagSecurityHelper.currentUser();
            if(user==null){
                return new Result(999,"当前用户信息为空");
            }

            if ((FieldHandler.isSentitive(exportSet.getFieldValue()) && !exportSet.getExportType().equals("2"))
                    || (!FieldHandler.isSentitive(exportSet.getFieldValue()) && exportSet.getExportType().equals("2"))){
                return new Result(-1,"导出字段跟导出类型不匹配！");
            }

            //判断导出任务是否涉及敏感信息比如手机号 身份证号等
            if (FieldHandler.isSentitive(exportSet.getFieldValue())){
                try {
                    return customerApprovalService.addCCISCommit(exportSet);
                }catch (Exception e){
                    log.error("敏感数据导出提交审批异常！"+e.getMessage());
                    return new Result(-1,"敏感数据导出提交审批异常！"+e.getMessage());
                }
            }else{
                boolean flag = customerApprovalService.checkExportSet(exportSet);
                String id = customerApprovalService.addCommit(exportSet.getCustomerId(), exportSet);
                if(flag|| SecurityHelper.containsPermission(Permissions.WORKFLOW_DEFINITION_10013.getCode())){
                    customerApprovalService.addPass(exportSet.getCustomerId(), id, user.getUserId());
                }
            }
        } catch (CustomersException e) {
            return new Result(e.getCode(), "操作失败");
        } catch (Exception e){
            log.error("自动审核 客群导出 通过 出错", e);
            return new Result(999, "操作失败");
        }
        return new Result(0);
    }


    /**
     * 导出客群审批通过
     *
     * @param customerId
     * @return
     */
    @ApiOperation(value = "导出客群审批通过", notes = "导出客群审批通过")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customerId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "流程实例ID"),
            @ApiImplicitParam(paramType = "query", name = "applicant", value = "申请人ID")
    })
    @PostMapping("addPass")
    public Result addPass(String customerId, String instanceId, String applicant) {
        customerApprovalService.addPass(customerId, instanceId, applicant);
        return new Result(0);
    }

    /**
     * 审批驳回
     *
     * @param customerId
     * @param desc
     * @return
     */
    @ApiOperation(value = "审批驳回", notes = "导出客群审批驳回")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customerId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "流程实例ID"),
            @ApiImplicitParam(paramType = "query", name = "applicant", value = "申请人ID"),
            @ApiImplicitParam(paramType = "query", name = "desc", value = "驳回原因")
    })
    @PostMapping("Reject")
    public Result reject(String customerId, String applicant, String instanceId, String desc) {
        customerApprovalService.reject(customerId, applicant,instanceId, desc);
        return new Result(0);
    }


    /**
     * 审批列表
     *
     * @param pageNumber
     * @param pageSize
     * @param customerName
     * @param approveType
     * @param approveState
     * @param uptTimeStart
     * @param uptTimeEnd
     * @return
     */
    @ApiOperation(value = "审批列表", notes = "组合标签审批列表")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页码"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数"),
            @ApiImplicitParam(paramType = "query", name = "customerName", value = "客群名"),
            @ApiImplicitParam(paramType = "query", name = "approveType", value = "申请类型"),
            @ApiImplicitParam(paramType = "query", name = "approveState", value = "审批状态"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeStart", value = "更新时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeEnd", value = "更新时间筛选（结束）")
    })
    @GetMapping("findList")
    public Result findList(Integer pageNumber, Integer pageSize, String customerName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        CustomersPage<ExportSet> customerPage = customerApprovalService.findList(pageNumber, pageSize, customerName, approveType, approveState, uptTimeStart, uptTimeEnd);
        return new Result(0, customerPage);
    }

    /**
     * 导出记录列表
     *
     * @param customerId
     * @param customerName
     * @param exportName
     * @param isready
     * @param approveState
     * @return
     */
    @ApiOperation(value = "导出记录列表", notes = "导出记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "页大小"),
            @ApiImplicitParam(paramType = "query", name = "customerId", value = "客群Id"),
            @ApiImplicitParam(paramType = "query", name = "customerName", value = "客群名"),
            @ApiImplicitParam(paramType = "query", name = "exportName", value = "导出名称"),
            @ApiImplicitParam(paramType = "query", name = "isready", value = "数据状态"),
            @ApiImplicitParam(paramType = "query", name = "approveState", value = "审批状态")
    })
    @GetMapping("findRecordList")
    public Result findRecordList(Integer pageNumber, Integer pageSize,String customerId,String customerName, String approveState, String exportName, String isready) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        CustomersPage<ExportSet> result = customerApprovalService.findRecordList(pageNumber, pageSize, customerId,
                customerName,
                approveState, exportName, isready);
        return new Result(0, result);
    }


    @ApiOperation(value = "导出下载重试", notes = "导出下载重试")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "数据主键")
    })
    @GetMapping("/retry")
    public Result retry(String id) {

        boolean retry = customerApprovalService.retry(id);
        if (retry){
            return new Result(0,"操作成功");
        }else {
            return new Result(-1,"操作失败");
        }
    }


    @ApiOperation(value = "导出下载异常状态调整", notes = "开发人员用")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "数据主键"),
            @ApiImplicitParam(paramType = "query", name = "isReady", value = "数据状态"),
            @ApiImplicitParam(paramType = "query", name = "reason", value = "失败理由")
    })
    @GetMapping("/test")
    public Result test(String id,String isReady,String reason) {
        customerApprovalService.test(id,isReady,reason);
        return new Result(0,"操作成功");
    }


    @ApiOperation(value = "修改数据文件发送状态", notes = "开发人员用")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "数据主键"),
            @ApiImplicitParam(paramType = "query", name = "sendStatus", value = "数据状态"),
            @ApiImplicitParam(paramType = "query", name = "zipName", value = "压缩包文件")
    })
    @GetMapping("/updateApply")
    public Result updateApply(String id,String sendStatus,String zipName) {
        customerApprovalService.updateApply(id,sendStatus,zipName);
        return new Result(0,"操作成功");
    }

    /**
     * 获取所有的申请类型
     *
     * @return
     */
    @ApiOperation(value = "获取所有的申请类型", notes = "组合标签审批类型")
    @GetMapping("findApproveType")
    public Result findApproveType() {
        Map map = customerApprovalService.findApproveType();
        return new Result(0, map);
    }

    /**
     * 查询某个流程的当前审批状态
     *
     * @param workflowId
     * @param customersId
     * @return
     */
    @ApiOperation(value = "查询某个流程的当前审批状态", notes = "审批状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "workflowId", value = "工作流Id"),
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群ID")
    })
    @GetMapping("findApprovalOne")
    public Result findApprovalOne(String workflowId, String customersId) {

        Customers customer = customerApprovalService.findApprovalOne(workflowId, customersId);
        return new Result(0, customer);
    }

    /**
     * 下载客群文件
     *
     * @return
     */
    @ApiOperation("下载客群文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "导出设置ID"),
            @ApiImplicitParam(paramType = "query", name = "userId", value = "下载人ID")
    })
    @GetMapping("/downLoad")
    public void downLoad(String id, String userId,HttpServletResponse response, HttpServletRequest request) {

        customerApprovalService.download(id, response,request);

    }

    @ApiOperation("敏感数据下载接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "导出设置ID"),
            @ApiImplicitParam(paramType = "query", name = "userId", value = "下载人ID"),
    })
    @GetMapping("/sensitiveDown")
    public Result sensitiveDown(String id,String userId) {
        try {
            return customerApprovalService.pushFile(id);
        }catch (Exception e){
            log.error("敏感数据下载接口调用异常！",e);
            return new Result(-1,"敏感数据下载接口调用异常"+e.getMessage());
        }
    }

    /**
     * 查询某个导出设置的详情
     *
     * @param customersId
     * @return
     */
    @ApiOperation(value = "查询某个导出设置的详情，主要用于回显数据", notes = "审批状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群ID"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "实例ID"),
            @ApiImplicitParam(paramType = "query", name = "applicant", value = "提交人ID")
    })
    @GetMapping("findExportInfo")
    public Result findExportInfo(String customersId,String instanceId,String applicant) {
        ExportSet set = customerApprovalService.findCustomerSet(customersId,instanceId,applicant);
        return new Result(0, set);
    }

    /**
     * 查询某个导出设置的详情
     * @param id
     * @return
     */
    @ApiOperation(value = "查询某个导出设置的详情，主要用于回显数据", notes = "审批状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键ID")
    })
    @GetMapping("findExportById")
    public Result findExportById(String id) {
        ExportSet set = customerApprovalService.findExportById(id);
        return new Result(0, set);
    }

    /**
     * 校验导出配置是否存在过
     * @param paramSet
     * @return
     */
    @ApiOperation(value = "校验导出配置是否存在过", notes = "boolean结果")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "paramSet", value = "SET设置")
    })
    @PostMapping("/checkExist")
    public Result findExportInfo(@RequestBody ExportSet paramSet) {
        log.info("exportSet="+paramSet.toString());
        boolean flag = customerApprovalService.checkExportSet(paramSet);
        return new Result(0, flag);
    }

    /**
     * 数据刷新按钮
     * @param exportSet
     * @return
     */
    @ApiOperation(value = "刷新数据", notes = "数据刷新")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "exportSet", value = "SET设置")
    })
    @PostMapping("/exportFlush")
    public Result exportFlush(@RequestBody ExportSet exportSet) {
        customerApprovalService.exportFlush(exportSet);
        return new Result(0);
    }

    //----------------------------------------客群发布审批流程-----------------------------------------------

    /**
     * 发布客群提交审批
     * @param customersId
     * @return
     */
    @ApiOperation(value = "客群发布提交申请", notes = "客群发布提交申请")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群ID")
    })
    @PostMapping("/releaseCommit")
    public Result releaseCommit(String customersId) {
        customerApprovalService.releaseCommit(customersId);
        return new Result(0);
    }


    /**
     * 客群发布审批通过
     *
     * @param customersId
     * @return
     */
    @ApiOperation(value = "客群发布审批通过", notes = "客群发布审批通过")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "流程实例ID")
    })
    @PostMapping("/releasePass")
    public Result releasePass(String customersId, String instanceId) {
        try {
            customerApprovalService.releasePass(customersId,instanceId);
            return new Result(0);
        }catch (Exception e){
            return new Result(999,"客群发布审批通过操作失败");
        }

    }

    /**
     * 发布客群审批驳回
     *
     * @param customersId
     * @param desc
     * @return
     */
    @ApiOperation(value = "发布客群审批驳回", notes = "发布客群审批驳回")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "实例ID"),
            @ApiImplicitParam(paramType = "query", name = "desc", value = "驳回原因")
    })
    @PostMapping("/releaseReject")
    public Result reject(String customersId, String instanceId ,String desc) {
        customerApprovalService.releasereject(customersId,instanceId,desc);
        return new Result(0);
    }

    /**
     * 发布客群重新提交审批
     *
     * @param customersId
     * @return
     */
    @ApiOperation(value = "发布客群重新提交审批", notes = "发布客群重新提交审批")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id")
    })
    @PostMapping("/releaseResubmit")
    public Result resubmit(String customersId) {
        customerApprovalService.releaseResubmit(customersId);
        return new Result(0);
    }

    /**
     * 发布客群的审批列表
     *
     * @param pageNumber
     * @param pageSize
     * @param customersName
     * @param approveType
     * @param approveState
     * @param uptTimeStart
     * @param uptTimeEnd
     * @return
     */
    @ApiOperation(value = "发布客群的审批列表", notes = "发布客群的审批列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页码"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数"),
            @ApiImplicitParam(paramType = "query", name = "customersName", value = "客群名"),
            @ApiImplicitParam(paramType = "query", name = "approveType", value = "申请类型"),
            @ApiImplicitParam(paramType = "query", name = "approveState", value = "审批状态"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeStart", value = "更新时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeEnd", value = "更新时间筛选（结束）")
    })
    @GetMapping("/findReleaseList")
    public Result findReleaseList(Integer pageNumber, Integer pageSize, String customersName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        CustomersPage<Customers> customerPage = customerApprovalService.findReleaseList(pageNumber, pageSize, customersName, approveType, approveState, uptTimeStart, uptTimeEnd);
        return new Result(0, customerPage);
    }

    //--------------------------------------------------------------------------------------------------
    /**
     * 删除客群提交审批
     * @param customersId
     * @return
     */
    @ApiOperation(value = "客群删除提交申请", notes = "客群删除提交申请")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群ID")
    })
    @PostMapping("/deleteCommit")
    public Result deleteCommit(String customersId) {
        customerApprovalService.deleteCommit(customersId);
        return new Result(0);
    }

    /**
     * 删除客群审批通过
     *
     * @param customersId
     * @return
     */
    @ApiOperation(value = "删除客群审批通过", notes = "删除客群审批通过")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "流程实例ID")
    })
    @PostMapping("/deletePass")
    public Result deletePass(String customersId, String instanceId) {
        customerApprovalService.deletePass(customersId,instanceId);
        return new Result(0);
    }

    /**
     * 删除客群审批驳回
     *
     * @param customersId
     * @param desc
     * @return
     */
    @ApiOperation(value = "删除客群审批驳回", notes = "删除客群审批驳回")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id"),
            @ApiImplicitParam(paramType = "query", name = "instanceId", value = "实例ID"),
            @ApiImplicitParam(paramType = "query", name = "desc", value = "驳回原因")
    })
    @PostMapping("/deleteReject")
    public Result deleteReject(String customersId, String instanceId ,String desc) {
        customerApprovalService.deleteReject(customersId,instanceId,desc);
        return new Result(0);
    }

    /**
     * 删除客群重新提交审批
     *
     * @param customersId
     * @return
     */
    @ApiOperation(value = "删除客群重新提交审批", notes = "删除客群重新提交审批")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群id")
    })
    @PostMapping("/deleteResubmit")
    public Result deleteResubmit(String customersId) {
        customerApprovalService.deleteResubmit(customersId);
        return new Result(0);
    }

    /**
     * 删除客群的审批列表
     *
     * @param pageNumber
     * @param pageSize
     * @param customersName
     * @param approveType
     * @param approveState
     * @param uptTimeStart
     * @param uptTimeEnd
     * @return
     */
    @ApiOperation(value = "删除客群的审批列表", notes = "删除客群的审批列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "页码"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "条数"),
            @ApiImplicitParam(paramType = "query", name = "customersName", value = "客群名"),
            @ApiImplicitParam(paramType = "query", name = "approveType", value = "申请类型"),
            @ApiImplicitParam(paramType = "query", name = "approveState", value = "审批状态"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeStart", value = "更新时间筛选（开始）"),
            @ApiImplicitParam(paramType = "query", name = "uptTimeEnd", value = "更新时间筛选（结束）")
    })
    @GetMapping("/findDeleteList")
    public Result findDeleteList(Integer pageNumber, Integer pageSize, String customersName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        CustomersPage<CustomersApprovalRecord> customerPage = customerApprovalService.findDelRecordList(pageNumber, pageSize, customersName, approveType, approveState, uptTimeStart, uptTimeEnd);
        return new Result(0, customerPage);
    }

    /**
     * 查询删除流程的当前审批状态
     *
     * @param workflowId
     * @param customersId
     * @return
     */
    @ApiOperation(value = "查询删除流程的当前审批状态", notes = "审批状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "workflowId", value = "工作流Id"),
            @ApiImplicitParam(paramType = "query", name = "customersId", value = "客群ID")
    })
    @GetMapping("/getStatus")
    public Result getStatus(String workflowId, String customersId) {
        String approverStatus = customerApprovalService.findDelById(customersId, workflowId);
        return new Result(0,(Object)approverStatus);
    }
}
